function refresh() {
    $("#dataTable").bootstrapTable("removeAll");
    $("#dataTable").bootstrapTable('refresh');
}
function showData(rptCode) {
    $$.goUrl('/iot/calcreport/calc_list.html?thirdMenuCode=OriginView&rptCode=' + rptCode);
}
function reviewRpt(rptCode,rptPeriod) {
    if(rptPeriod==1){
        $$.goUrl('/iot/rptPreview/previewDayRpt.html?thirdMenuCode=OriginView&rptCode=' + rptCode+'&rptPeriod='+rptPeriod);

    }else{
        $$.goUrl('/iot/rptPreview/previewMonthRpt.html?thirdMenuCode=OriginView&rptCode=' + rptCode+'&rptPeriod='+rptPeriod);

    }
}

function modifyCatalog(data) {
    var rows = $("#dataTable").bootstrapTable('getSelections');
    var rowIds = [];
    for (var i = 0; i < rows.length; i++) {
        rowIds.push(rows[i].id);
    }
    var catalogId = data.catalogId;
    if (catalogId == 1) {
        catalogId = -1;
    }
    $$.ajax({
        url: "/rest/IotReportBusiness/modifyBatch",
        data: {
            catalogId: catalogId,
            id: rowIds.join(",")
        },
        success: function (data) {
            layer.msg('设置成功', {time: 2000});
        }
    });
    refresh();
}

//搜索以前将页码换成第一页
function searchBeforeInit() {
    var options = $("#dataTable").bootstrapTable("getOptions");
    options.pageNumber = 1;
    $("#dataTable").bootstrapTable('refreshOptions', options);
}

function initSearchEvent() {

    $("#serachBtn").click(function () {
        searchBeforeInit();
        refresh();
    });
    $('#serachBtn').bind('keypress', function (e) {


        if (e.keyCode == 13) {
            searchBeforeInit();
            refresh();
        }
    });
    $('#seachValue1').bind('keypress', function (e) {

        if (e.keyCode == 13) {
            searchBeforeInit();
            refresh();
        }
    });
    $('#seachValue2').bind('keypress', function (e) {

        if (e.keyCode == 13) {
            searchBeforeInit();
            refresh();
        }
    });
    $("#searchReset").on("click", function () {
        //$("#searchForm")[0].reset();
        $("#searchForm input[type='text']").val("");
    });

    $("#del-btn").click(function () {
        var len = $("#dataTable input:checked").length;
        if (len == 0) {
            //未选中数据提示框
            layer.msg('请选择数据', {time: 1000});
        } else {
            deleteData();

        }

    });

    //新建弹框
    $("#add-btn").on('click', function () {
        addData();
    });
    //设置分类
    $("#catalog-btn").on('click', function () {
        var len = $("#dataTable input:checked").length;
        if (len == 0) {
            //未选中数据提示框
            layer.msg('请选择数据', {time: 2000});
        } else {


            layer.open({
                move: false,
                type: 2,
                title: '设置采集点分类',
                area: ['900px', '500px'],
                content: 'catalog_select.html',
                btn: ['确定', '取消'],
                btnAlign: 'c',
                yes: function (index, layero) {
                    var openWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                    var ret = openWin.yesOperator();
                    if (ret == null) {

                    } else {


                        modifyCatalog(ret);
                        layer.close(index);
                    }

                }, cancel: function (index) {
                    layer.close(index);
                }
            });
        }
    });

}

function editData(rowId) {
    layer.open({
        move: false,
        type: 2,
        title: '新建',
        area: ['800px', '420px'],
        content: 'report_update.html?rowId=' + rowId,
        btn: ['保存', '取消'],
        btnAlign: 'c',
        yes: function (index, layero) {
            var openWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
            var ret = openWin.yesOperator();
            if (ret) {
                layer.close(index);
                refresh();
            }
        }, cancel: function (index) {
            layer.close(index);
        }
    });
}

function deleteData() {
    layer.confirm('确定要删除这条数据吗？',
        {icon: 3, title: '提示', area: '300px', btnAlign: 'c'}, function (index) {
            var rows = $("#dataTable").bootstrapTable('getSelections');
            var rowIds = [];
            for (var i = 0; i < rows.length; i++) {
                rowIds.push(rows[i].id);
            }
            $$.ajax({
                url: "/rest/IotReportBusiness/remove",
                data: {
                    id: rowIds.join(',')
                },
                success: function () {
                    refresh();
                }
            });
            layer.close(index);
        });
}

function addData() {
    layer.open({
        move: false,
        type: 2,
        title: '新建',
        area: ['800px', '420px'],
        content: 'report_add.html',
        btn: ['保存', '取消'],
        btnAlign: 'c',
        yes: function (index, layero) {
            var openWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
            var ret = openWin.yesOperator();
            if (ret) {
                layer.close(index);
                refresh();
            }
        }, cancel: function (index) {
            layer.close(index);
        }
    });
}


function refreshTree() {
    $("#treeParent").empty();
    $("#treeParent").append('<div id="treeTable"></div>');
    initTree();
}

function initTree() {
    //左侧树列表
    //tree


    var DataSource = [];
    $$.ajax({
        url: "/rest/IotReportCatalogBusiness/listAllSort",
        async: false,
        data: {
            menuCode: ""
        },
        success: function (data) {
            //console.log("listByMenuId:"+JSON.stringify(data));
            DataSource = data;
        }
    });


    var source = {
        dataType: "json",
        dataFields: [{
            name: "catalogId",
            type: "string",

        }, {
            name: "catalogName",
            type: "string",
        }, {
            name: 'children',
            type: 'array'
        }, {
            name: 'expanded',
            type: 'bool'
        }],
        hierarchy: {
            root: 'children'
        },
        id: 'catalogId',
        localData: DataSource
    };
    var dataAdapter = new $.jqx.dataAdapter(source);
    var iHeight = $('#rightCont').height() - 30;
    // create Tree Grid
    $("#treeTable").jqxTreeGrid({
        source: dataAdapter,
        width: '100%',
        altRows: true,
        selectionMode: "singleRow",
        height: iHeight,
        theme: 'bootstrap',
        showToolbar: false,
        enableHover: true,
        columns: [{
            text: "分类",
            align: "center",
            dataField: "catalogName",
            cellsRenderer: function (row, column, value, rowData) {

                var container = "";
                if (rowData.catalogId == -1 || rowData.catalogId == -9999) {
                    container = '<span style="width: 100%; height: 100%;">';
                    var data = '<span class="tree-item-text" title=" ' + value + ' ">' + value + '</span>'
                    var option = '<span class="rt tree-item-opt hidden">' +
                        '<a href="javascript:void(0)"><i class="glyphicon glyphicon-plus" onclick="addClassify(event,\'' + rowData.catalogId + '\')"></i></a>' +
                        '</span>';
                    container += data;
                    container += option;
                    container += "</span>";
                } else {
                    container = '<span style="width: 100%; height: 100%;">';
                    var data = '<span class="tree-item-text" title=" ' + value + ' ">' + value + '</span>'
                    var option = '<span class="rt tree-item-opt hidden">' +
                        '<a href="javascript:void(0)"><i class="glyphicon glyphicon-plus" onclick="addClassify(event,\'' + rowData.catalogId + '\')"></i></a>' +
                        '<a href="javascript:void(0)"><i class="glyphicon glyphicon-pencil" onclick="editClassify(event,\'' + rowData.catalogId + '\')"></i></a>' +
                        '<a href="javascript:void(0)"><i class="glyphicon glyphicon-trash" onclick="delClassify(event,\'' + rowData.catalogId + '\')"></i></a></span>';
                    container += data;
                    container += option;
                    container += "</span>";
                }
                return container;
            },
        }],
        ready: function () {
            classifyOpt();
        }
    });
    /*
    //收起子菜单鼠标悬浮操作
    $("#treeTable").on('rowCollapse', function (event) {
        classifyOpt();
    });
    //展开子菜单鼠标悬浮操作
    $("#treeTable").on('rowExpand', function (event) {
        classifyOpt();
    });
    */
    //点击左边tree,右侧table refresh
    $("#treeTable").on('rowSelect', function (event) {

        var eo = window.event || arguments.callee.caller.arguments[0];
        var target=eo.target || eo.srcElement

        if (window.event) {
            var tagName = eo.target.tagName;
            //alert(event.source);
            //如果是单击分类信息
            if (tagName == "SPAN" || tagName == "TD") {
                var row = event.args.row;
                $("#dataCatalog").val(row.catalogId);
                refresh();
                //alert(row.DataSourceID+"-"+row.stockName+"-"+row.expanded);
                //$("#dataTable").bootstrapTable('refresh');
            }
        } else {
            var row = event.args.row;
            $("#dataCatalog").val(row.catalogId);
            refresh();

        }

    });

}


//新建报表
function addReport(e) {
    e = e || window.event;
    layer.open({
        move: false,
        type: 2,
        title: '新建报表',
        area: ['545px', '200px'],
        content: 'report_add.html',
        btn: ['确定', '取消'],
        btnAlign: 'c',
        yes: function (index, layero) {
            var openWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
            var form = openWin.submitForm();
            if (!form) {
                layer.close(index);
            }
        }, cancel: function (index) {
            layer.close(index);
        }
    });
    e.stopPropagation();
}

function classifyOpt() {
    $("#treeTable").on("mouseover mouseout","tr",function(event){
        console.log(event.type);
        if(event.type == 'mouseover'){
            $(this).find('.rt').removeClass('hidden');
        }else{
            $(this).find('.rt').addClass('hidden');
        }
    });



}

//新建分类弹出框
function addClassify(e, data) {
    e = e || window.event;

    if (data == -1 || data == -9999) {
        data = 0;
    }

    layer.open({
        move: false,
        type: 2,
        title: '新建分类',
        area: ['500px', '200px'],
        content: 'report_classify_add.html?rowId=' + data,
        btn: ['确定', '取消'],
        btnAlign: 'c',
        yes: function (index, layero) {
            var openWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
            var ret = openWin.yesOperator();
            if (ret) {
                layer.close(index);
                refreshTree();
            }
        }, cancel: function (index) {
            layer.close(index);
        }
    });
    e.stopPropagation();
}

//编辑分类弹出框
function editClassify(e, data) {
    e = e || window.event;
    layer.open({
        move: false,
        type: 2,
        title: '编辑分类',
        area: ['500px', '200px'],
        content: 'report_classify_update.html?rowId=' + data,
        btn: ['确定', '取消'],
        btnAlign: 'c',
        yes: function (index, layero) {
            var openWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
            var ret = openWin.yesOperator();
            if (ret) {
                layer.close(index);
                refreshTree();
            }
        }, cancel: function (index) {
            layer.close(index);
        }
    });
    e.stopPropagation();
}

//删除分类弹出框
function delClassify(e, data) {
    e = e || window.event;
    layer.confirm('确定要删除分类吗？',
        {icon: 3, title: '提示', area: '300px', btnAlign: 'c'}, function (index) {

            $$.ajax({
                url: "/rest/IotReportCatalogBusiness/remove",
                data: {
                    id: data
                },
                success: function () {
                    layer.close(index);
                    refreshTree();
                }
            });

        });
    e.stopPropagation();
}

$(function () {
    initTree();
    initSearchEvent();
    //渲染表格
    var columns = reportList.columnsInit();
    var table = reportList.gridInit(columns);
    //var datas = reportList.dataInit();
    // $("#dataTable").bootstrapTable("append", datas);
})
;(function (undefined) {
    "use strict"
    var _global;

    function result(args, fn) {
        var argsArr = Array.prototype.slice.call(args);
        if (argsArr.length > 0) {
            return argsArr.reduce(fn);
        } else {
            return 0;
        }
    }

    var reportList = {
        columnsInit: function () {
            return [
                {
                    field: 'status',
                    title: '序号',
                    formatter: function (value, row, index) {
                        return index + 1;
                    }
                },
                {
                    field: "rptCode", title: "报表编码",
                    sortable: true
                },
                {field: "rptName", title: "报表名称"},
                {field: "catalogName", title: "分类"},
                {field: "rptPeriod", title: "周期",
                    formatter: function (value, row, index) {
                        if (value == '1') {
                            return [
                                '日报'
                            ];
                        }
                        return [
                            '月报'
                        ];

                    }

                },
                {field: "rowSort", title: "排序号"},
                {
                    field: 'status',
                    title: '状态',
                    formatter: function (value, row, index) {
                        if (value == '1') {
                            return [
                                '<span class="sys-type-bg pro-status-green">启用</span>'
                            ];
                        }
                        return [
                            '<span class="sys-type-bg pro-status-red">停用</span>'
                        ];

                    }

                },
                {
                    field: 'optionDel',
                    checkbox: true
                }, {
                    field: 'option',
                    title: '操作',
                    width: 80,
                    align: 'center',
                    formatter: function (value, row, index) {

                        return [
                            '<div class="opt-dropdown tb-opt-div"><a class="tb-opt-icon" href="javascript:void(0)">操作 <i class="glyphicon glyphicon-triangle-bottom"></i></a>',
                            '<ul class="opt-dropdown-menu opt-dropdown-menu-bottom">',
                            '<li><a href="javascript:editData(\'' + row.id + '\')" title="编辑">',
                            '<i class="glyphicon glyphicon-pencil"></i><em> 编辑</em></a></li>',
                            '<li><a href="javascript:showData(\'' + row.rptCode + '\')" ><i class="glyphicon glyphicon-th-list"></i><em> 详细数据</em></a></li>',
                            '<li><a href="javascript:reviewRpt(\'' + row.rptCode + '\',\''+row.rptPeriod+'\')" ><i class="glyphicon glyphicon-search"></i><em> 报表预览</em></a></li>',
                            '</ul></div>'


                        ].join('');
                    }

                }]
        },
        gridInit: function (columns) {
            return $("#dataTable").bootstrapTable({
                method: "post",
                contentType: "application/x-www-form-urlencoded",
                url: $$.restServerUrl + '/bootstrap/basegrid/IotReportBusiness/list',
                columns: columns,
                undefinedText: '-',
                striped: 'true',
                classes: 'table table-hover qxttable',
                pagination: 'true',
                clickToSelect: true,
                singleSelect: false,
                sidePagination: "server",
                queryParamsType: "page",
                sortSide: 'client',
                sortable: true,
                pageNumber: 1,
                pageSize: 10,
                idField: 'id',
                silentSort: true,
                pageList: [
                10,20,50,100
                ],
                onClickRow: function (row, $element, field) {
                    $("#dataTable").bootstrapTable("uncheckAll");
                },
                queryParams: function queryParams(params) {   //设置查询参数

                    var args = {};
                    var catalogId = $("#dataCatalog").val();
                    if (catalogId.length > 0 && catalogId != -9999) {
                        args.c_catalogId_1 = catalogId;
                    }
                    args.c_rptCode_7 = $("#seachValue1").val();
                    args.c_rptName_7 = $("#seachValue2").val();
                    args.page = params.pageNumber - 1; //    params.pageNumber
                    args.pageSize = params.pageSize;     //params.pageSize
                    args.isPage = 1;
                    //args.order=orderStr;
                    var paramStr = JSON.stringify(args);

                    //alert(params.pageNumber+":"+params.pageSize);
                    //alert(orderStr);
                    var param = {
                        params: paramStr
                    };
                    return param;
                },
                onPostBody: function () {
                    $(".opt-dropdown").each(function (index, data) {
                        var _this = this;
                        $(this).hover(function () {
                            $(_this).find(".opt-dropdown-menu").show();
                        }, function () {
                            $(_this).find(".opt-dropdown-menu").hide();
                        })
                    });
                    var minHeight = $("#rightCont").height() -30;
                    var maxheight = $("#dataTable").height() + 100;
                    if(maxheight < minHeight){
                        $("#treeTable").jqxTreeGrid({
                            height:minHeight
                        })
                    } else if(maxheight > minHeight){
                        $("#treeTable").jqxTreeGrid({
                            height:maxheight
                        })
                    }
                   // classifyOpt();
                }
            })
        },
        dataInit: function () {
            return []
        }
    }

    // 将插件对象暴露给全局对象
    _global = (function () {
        return this || (0, eval)('this');
    }());
    if (typeof module !== "undefined" && module.exports) {
        module.exports = reportList;
    } else if (typeof define === "function" && define.amd) {
        define(function () {
            return reportList;
        });
    } else {
        !('plugin' in _global) && (_global.reportList = reportList);
    }
}());